package com.mall.config;

import org.quartz.Scheduler;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;
import java.util.Properties;

@Configuration
public class QuartzSchedulerConfig {

    @Autowired
    private MyJobFactory jobFactory;

    /**
     * 加载配置文件
     * @return
     * @throws IOException
     */
    @Bean
    public Properties getProperties() throws IOException{
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        //加载属性文件
        bean.setLocation(new ClassPathResource("/quartz.properties"));
        //当属性文件被读取后才进行初始化
        bean.afterPropertiesSet();
        return bean.getObject();

    }

    /**
     * 配置调度器工厂
     * @return
     * @throws IOException
     */
    @Bean
    public SchedulerFactoryBean factoryBean() throws  IOException{
        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
        factoryBean.setQuartzProperties(getProperties());
        factoryBean.setJobFactory(jobFactory);
        return factoryBean;
    }

    /**
     * 配置调度器
     * @return
     */
    @Bean
    public Scheduler scheduler(){
        try {
            return factoryBean().getScheduler();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 监听器
     * @return
     */
    @Bean
    public QuartzInitializerListener listener(){
        return new QuartzInitializerListener();
    }

}
